package com.os4j.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class FastjsonArrayUtils extends FastjsonUtils {
	
	private List<Object> insertList;
    private List<Object> deleteList;
    private List<Object> updateList;

    public FastjsonArrayUtils() {
      insertList = new ArrayList<Object>();
      deleteList = new ArrayList<Object>();
      updateList = new ArrayList<Object>();
    }
    
	public Map<String, Object> compartr(Map<String, Object> map, String key, JSONArray ja1, JSONArray ja2) {
		List<Object> cl1;
		List<Object> cl2;
		String className,id;
		if ("creditLine".equals(key)){
			clear();
			id = "id";
			className = "com.os4j.model.CreditLine";
		}else if ("materialList".equals(key)){
			clear();
			className = "com.os4j.model.MaterialCompart";
			id = "materialId";
		} else if ("attributeList".equals(key)){
			clear();
			className = "com.os4j.model.AttributeValueDTO";
			id = "attributeDefinitionId";
		} else {
			return map;
		}
		Class clazz = super.getClassByName(className);
		cl1 = super.JSONArray2JavaList(ja1,clazz);
		cl2 = super.JSONArray2JavaList(ja2,clazz); 
		compartr(cl1, cl2);
		Map<String,Object> tmap = new TreeMap<String,Object>();
		if(!insertList.isEmpty())
			tmap.put("insert", super.list2JSONArray(insertList));
		if(!deleteList.isEmpty())
			tmap.put("delete", super.list2JSONArray(deleteList));
		cl1.retainAll(updateList);
		cl2.retainAll(updateList);
		Map cmap = new TreeMap();
		for (Object c : cl1) {
			Object cl = cl2.get(cl2.indexOf(c));
			Map<String,Object> pmap = new TreeMap<String,Object>();
			super.compartr(pmap, super.java2JSONOject(c), super.java2JSONOject(cl));
			JSONObject json = super.java2JSONOject(cl);
			if(!pmap.isEmpty())
				cmap.put(json.get(id), pmap);
		}
		if(!cmap.isEmpty())
			tmap.put("update", cmap);
		if(!tmap.isEmpty())
			map.put(key, tmap);
		return map;
	}
	
	public void clear(){
		insertList.clear();
		deleteList.clear();
		updateList.clear();
	}
	
	public void compartr(List<Object> l1,List<Object> l2){
		if (l1 == null && l2 == null)
	      return;
	    // 全部删除
	    if (l2.isEmpty()) {
	    	deleteList = l1;
	    	return;
	    }
	    // 全部新增
	    if (l1.isEmpty()) {
	    	insertList = l2;
	    	return;
	    }
	    // 有新增+更新+删除
	    for (Object obj : l2) {
	      // 更新的
	      if (l1.contains(obj))
	    	  updateList.add(obj);
	      else
	    	  insertList.add(obj);// 新增的
	    }
	    // 要删的
	    for (Object obj : l1)
	      if (!l2.contains(obj))
	    	  deleteList.add(obj);
	}
}